package com.mhl.client;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.logging.LogRecord;

// 用于存储网络操作的工具类，建议放静态函数
public class HttpUtil {
    private Bitmap tempBitmap;

    public static final int CHANGE_UI = 1;

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    tempBitmap = (Bitmap) msg.obj;
                    break;
                default:
                    break;
            }
        }
    };

    public class WorkThread extends Thread {
        public String url;

        public WorkThread(String url) {
            this.url = url;
        }
        @Override
        public void run() {
            /**
             * 耗时操作
             */
            try {
                URL webUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection)webUrl.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                if(conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    // 向handler发送消息
                    Message msg = Message.obtain();
                    msg.what = CHANGE_UI;
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public Bitmap getHttpBitmap(String url){
        new WorkThread(url).start();
        return tempBitmap;
    }

    public static Bitmap getBitmapFromUrl(String path) {
        final Bitmap[] bitmap = {null};
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    if(conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        bitmap[0] = BitmapFactory.decodeStream(is);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return bitmap[0];
    }
}
